//
//  BiYingH5BaseController.m
//  BiYing
//
//  Created by 周围 on 2017/10/10.
//  Copyright © 2017年 grx. All rights reserved.
//

#import "LYouH5BaseController.h"
#import "UIView+Extension.h"
#import <WebKit/WebKit.h>

@interface LYouH5BaseController () <WKUIDelegate, WKNavigationDelegate>

@property (strong, nonatomic) WKWebViewConfiguration *wkConfig;

@property (copy, nonatomic) NSString *H5Title;
@property (copy, nonatomic) NSString *h5Url;
@property (nonatomic, strong) UILabel *titleLable;
@property(nonatomic,strong) UIButton *backButton;


@end

@implementation LYouH5BaseController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = ColorWithHexRGB(0x1F1E23);
    self.progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, NavigbarTopMargin, SCREEN_WIDTH, 1)];
    self.progressView.backgroundColor = ColorWithHexRGB(0xE5E5E5);
    self.progressView.progressTintColor= ColorWithHexRGB(0x1F1E23);;
    //设置进度条的高度
    self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
    [self.view addSubview:self.progressView];
    
    
}

- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];
    [self setAutomaticallyAdjustsScrollViewInsets:NO];
    self.wkWebView.y = NavigbarTopMargin;
    self.wkWebView.height = self.view.height - NavigbarTopMargin;
}

-(void)backClick
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)startLoadWithTitle:(NSString *)title url:(NSString *)url {
    [LYouLoadingView show];
//    NSSet *types = [NSSet setWithArray:@[WKWebsiteDataTypeDiskCache,
//                                         WKWebsiteDataTypeMemoryCache]];
//    NSDate *dateFrom = [NSDate date];
//    [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:types modifiedSince:dateFrom completionHandler:^{
    
//        self.titleLable.text = title;
//        self.navigationItem.titleView = self.titleLable;
//        self.titleLable.sd_layout.topSpaceToView(self.navigationItem.titleView, 0).centerXEqualToView(self.navigationItem.titleView).widthIs(kWidth(200)).heightIs(navBarHeight - 20);
    self.title = title;
    [self.navigationController.navigationBar setTitleTextAttributes:
  @{NSFontAttributeName:[UIFont systemFontOfSize:17],
    NSForegroundColorAttributeName:ColorWithHexRGB(0x2d2d2d)}];
        self.H5Title = title;
        self.h5Url = url;
        NSString *urlString = url;
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
        request.timeoutInterval = 15.0f;
        [self.wkWebView loadRequest:request];
        _wkWebView.frame = CGRectMake(0, NavigbarTopMargin, SCREEN_WIDTH, SCREEN_HEIGHT - NavigbarTopMargin-TabbarSafeBottomMargin);
        _wkWebView.navigationDelegate = self;
        _wkWebView.UIDelegate = self;
//        _wkWebView.scrollView.backgroundColor = ColorWithHexRGB(0x1F1E23);
        _wkWebView.scrollView.showsVerticalScrollIndicator = NO;
//        _wkWebView.scrollView.scrollEnabled = NO;
        [self.view addSubview:_wkWebView];
        /** 返回按钮 */
        [self.view addSubview:self.backButton];
        [self.backButton setFtCornerdious:35/2 Corners:UIRectCornerTopRight|UIRectCornerBottomRight];
//    }];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        self.progressView.progress = self.wkWebView.estimatedProgress;
        if (self.progressView.progress == 1) {
            
            __weak typeof (self)weakSelf = self;
            [UIView animateWithDuration:0.25f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
            } completion:^(BOOL finished) {
                weakSelf.progressView.hidden = YES;
                if ([[AFNetworkReachabilityManager sharedManager] networkReachabilityStatus] == AFNetworkReachabilityStatusNotReachable) {
                }
            }];
        }
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

#pragma mark --- WKWKNavigationDelegate
//开始加载
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    self.progressView.hidden = NO;
    self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
    //防止progressView被网页挡住
    [self.view bringSubviewToFront:self.progressView];
}

//加载完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
//    self.progressView.hidden = YES;
    [LYouLoadingView hide];
    [webView evaluateJavaScript:@"document.documentElement.style.webkitTouchCallout='none';" completionHandler:nil];
    [webView evaluateJavaScript:@"document.documentElement.style.webkitUserSelect='none';"completionHandler:nil];
}

//加载失败
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    [LYouLoadingView hide];
    self.progressView.hidden = YES;
}

- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    [LYouLoadingView hide];
}

//页面跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    // 获取完整url并进行UTF-8转码
    decisionHandler(WKNavigationActionPolicyAllow);
}

#pragma mark --- 懒加载
- (WKWebViewConfiguration *)wkConfig {
    if (!_wkConfig) {
        _wkConfig = [[WKWebViewConfiguration alloc] init];
        _wkConfig.allowsInlineMediaPlayback = YES;
        _wkConfig.allowsPictureInPictureMediaPlayback = YES;
    }
    return _wkConfig;
}

- (WKWebView *)wkWebView {
    if (!_wkWebView) {
        _wkWebView = [[WKWebView alloc] init];
        //监听WKWebView加载网页进度的estimatedProgress属性。
        [self.wkWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    }
    return _wkWebView;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

- (void)dealloc {
    [self.wkWebView removeObserver:self forKeyPath:@"estimatedProgress"];
}

//- (UILabel *)titleLable{
//    if (_titleLable == nil) {
//        _titleLable = [UILabel new];
//        _titleLable.font = UIFontSystem17;
//        _titleLable.textColor = UIColorHigRedTheme;
//        _titleLable.textAlignment = NSTextAlignmentCenter;
//    }
//    return _titleLable;
//}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (UIButton *)backButton {
    if (!_backButton) {
        _backButton = [UIButton new];
        CGFloat safeBottem = MainWindows.safeAreaInsets.bottom;
        CGFloat hight = 28;
        if (safeBottem>0) {
            hight = 48;
        }
        _backButton.frame = CGRectMake(0, hight, 45, 35);
        [_backButton setImage:[UIImage imageNamed:@"backLeftBg"] forState:UIControlStateNormal];
        [_backButton setImage:[UIImage imageNamed:@"backLeftBg"] forState:UIControlStateHighlighted];
        [_backButton addTarget:self action:@selector(backButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        _backButton.layer.borderWidth = 1;
    }
    return _backButton;
}
-(void)backButtonClick:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
